xquery version "1.0-ml";

import module namespace plib = "http://porvino.com/lib" at "/porvino/lib/lib.xqy";
import module namespace text-input = "http://www.porvino.com/text-input" at "/porvino/text-input/text-input.xqy";

let $cid := xdmp:get-request-field("cid")
let $host := xdmp:get-request-field("host")
let $did := xdmp:get-request-field("did")
let $dbase := xdmp:get-request-field("dbase")
let $val := xdmp:get-request-field("val")

let $element := fn:tokenize($dbase, "/")[last()]
let $dbase-back := fn:substring($dbase, 0, fn:string-length($dbase) - fn:string-length($element)  )

let $docpath := fn:concat("fn:doc('",$did,"')",$dbase)
let $doc := xdmp:eval($docpath)

return
    let $update-text-node :=
        fn:concat(
            "xdmp:node-replace(",
                $docpath,
                ",",
                "<",$element,">",
                $val,
                "</",$element,">",
            ")"
        )
     let $insert-text-node :=
        let $docpath-back := fn:concat("fn:doc('",$did,"')",$dbase-back)
        return
        fn:concat(
            "xdmp:node-insert-child(",
                $docpath-back,
               ",",
               "<",$element,">",
                $val,
                "</",$element,">",
            ")"
        )


    return
    if (fn:exists($doc))
    then
        xdmp:eval($update-text-node)    
    else
        xdmp:eval($insert-text-node)



           
           
              
